<template>
  <div class="math-editor-overlay" @click.self="handleClose">
    <div class="math-editor-container">
      <div class="math-editor-header">
        <h3>插入数学公式</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      
      <div class="math-editor-body">
        <!-- 预览区域 -->
        <div class="preview-section">
          <div class="section-label">
            实时预览
            <span class="help-badge">所见即所得</span>
          </div>
          <div class="preview-box">
            <div v-if="formula" class="formula-preview" v-html="renderedFormula"></div>
            <div v-else class="preview-placeholder">
              <svg viewBox="0 0 24 24" width="48" height="48" fill="currentColor" opacity="0.3">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
              </svg>
              <p>点击下方符号按钮或直接输入LaTeX代码</p>
              <p class="sub-text">实时预览数学公式效果</p>
            </div>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="input-section">
          <div class="section-label">
            LaTeX 公式
            <span class="help-text">（点击下方符号按钮快速插入，或直接输入代码）</span>
          </div>
          <textarea 
            v-model="formula"
            class="formula-input"
            placeholder="点击下方符号按钮插入公式，或直接输入 LaTeX 代码..."
            rows="3"
          ></textarea>
        </div>
        
        <!-- 常用符号面板 -->
        <div class="symbols-section">
          <div class="section-label">常用符号</div>
          <div class="symbols-tabs">
            <button 
              v-for="tab in symbolTabs" 
              :key="tab.id"
              :class="['tab-btn', { active: currentTab === tab.id }]"
              @click="currentTab = tab.id"
            >
              {{ tab.name }}
            </button>
          </div>
          <div class="symbols-grid">
            <button 
              v-for="symbol in currentSymbols" 
              :key="symbol.latex"
              class="symbol-btn"
              @click="insertSymbol(symbol.latex)"
              :title="symbol.name"
            >
              <span v-html="symbol.display"></span>
            </button>
          </div>
        </div>
        
        <!-- 示例 -->
        <div class="examples-section">
          <div class="section-label">常用示例</div>
          <div class="examples-list">
            <button 
              v-for="example in examples" 
              :key="example.latex"
              class="example-btn"
              @click="formula = example.latex"
            >
              <span class="example-preview" v-html="renderFormula(example.latex)"></span>
              <span class="example-label">{{ example.name }}</span>
            </button>
          </div>
        </div>
      </div>
      
      <div class="math-editor-footer">
        <button class="btn btn-cancel" @click="handleClose">取消</button>
        <button class="btn btn-insert" :disabled="!formula.trim()" @click="handleInsert">
          插入公式
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import katex from 'katex'
import 'katex/dist/katex.min.css'

const emit = defineEmits(['close', 'insert'])

const formula = ref('')
const renderedFormula = ref('')
const currentTab = ref('basic')

// 监听formula变化，自动更新预览
watch(formula, () => {
  updatePreview()
}, { immediate: true })

// 符号分类
const symbolTabs = [
  { id: 'basic', name: '基础' },
  { id: 'greek', name: '希腊字母' },
  { id: 'operator', name: '运算符' },
  { id: 'relation', name: '关系符' },
  { id: 'arrow', name: '箭头' },
  { id: 'special', name: '特殊' }
]

// 符号库 - 使用完整示例而不是空占位符
const symbols = {
  basic: [
    { latex: '\\frac{a}{b}', display: renderFormula('\\frac{a}{b}'), name: '分数' },
    { latex: '\\sqrt{x}', display: renderFormula('\\sqrt{x}'), name: '根号' },
    { latex: '\\sqrt[n]{x}', display: renderFormula('\\sqrt[n]{x}'), name: 'n次根号' },
    { latex: 'x^{n}', display: renderFormula('x^{n}'), name: '上标' },
    { latex: 'x_{n}', display: renderFormula('x_{n}'), name: '下标' },
    { latex: '\\sum_{i=1}^{n}', display: renderFormula('\\sum_{i=1}^{n}'), name: '求和' },
    { latex: '\\prod_{i=1}^{n}', display: renderFormula('\\prod_{i=1}^{n}'), name: '连乘' },
    { latex: '\\int_{a}^{b}', display: renderFormula('\\int_{a}^{b}'), name: '积分' },
    { latex: '\\iint', display: renderFormula('\\iint'), name: '二重积分' },
    { latex: '\\iiint', display: renderFormula('\\iiint'), name: '三重积分' },
    { latex: '\\lim_{x \\to a}', display: renderFormula('\\lim_{x \\to a}'), name: '极限' },
    { latex: '\\infty', display: renderFormula('\\infty'), name: '无穷' }
  ],
  greek: [
    { latex: '\\alpha', display: renderFormula('\\alpha'), name: 'α' },
    { latex: '\\beta', display: renderFormula('\\beta'), name: 'β' },
    { latex: '\\gamma', display: renderFormula('\\gamma'), name: 'γ' },
    { latex: '\\delta', display: renderFormula('\\delta'), name: 'δ' },
    { latex: '\\epsilon', display: renderFormula('\\epsilon'), name: 'ε' },
    { latex: '\\theta', display: renderFormula('\\theta'), name: 'θ' },
    { latex: '\\lambda', display: renderFormula('\\lambda'), name: 'λ' },
    { latex: '\\mu', display: renderFormula('\\mu'), name: 'μ' },
    { latex: '\\pi', display: renderFormula('\\pi'), name: 'π' },
    { latex: '\\sigma', display: renderFormula('\\sigma'), name: 'σ' },
    { latex: '\\phi', display: renderFormula('\\phi'), name: 'φ' },
    { latex: '\\omega', display: renderFormula('\\omega'), name: 'ω' },
    { latex: '\\Gamma', display: renderFormula('\\Gamma'), name: 'Γ' },
    { latex: '\\Delta', display: renderFormula('\\Delta'), name: 'Δ' },
    { latex: '\\Theta', display: renderFormula('\\Theta'), name: 'Θ' },
    { latex: '\\Lambda', display: renderFormula('\\Lambda'), name: 'Λ' },
    { latex: '\\Sigma', display: renderFormula('\\Sigma'), name: 'Σ' },
    { latex: '\\Phi', display: renderFormula('\\Phi'), name: 'Φ' },
    { latex: '\\Omega', display: renderFormula('\\Omega'), name: 'Ω' }
  ],
  operator: [
    { latex: '+', display: renderFormula('+'), name: '加' },
    { latex: '-', display: renderFormula('-'), name: '减' },
    { latex: '\\times', display: renderFormula('\\times'), name: '乘' },
    { latex: '\\div', display: renderFormula('\\div'), name: '除' },
    { latex: '\\pm', display: renderFormula('\\pm'), name: '正负' },
    { latex: '\\mp', display: renderFormula('\\mp'), name: '负正' },
    { latex: '\\cdot', display: renderFormula('\\cdot'), name: '点乘' },
    { latex: '\\ast', display: renderFormula('\\ast'), name: '星号' },
    { latex: '\\circ', display: renderFormula('\\circ'), name: '圆圈' },
    { latex: '\\bullet', display: renderFormula('\\bullet'), name: '实心点' },
    { latex: '\\cup', display: renderFormula('\\cup'), name: '并集' },
    { latex: '\\cap', display: renderFormula('\\cap'), name: '交集' }
  ],
  relation: [
    { latex: '=', display: renderFormula('='), name: '等于' },
    { latex: '\\neq', display: renderFormula('\\neq'), name: '不等于' },
    { latex: '<', display: renderFormula('<'), name: '小于' },
    { latex: '>', display: renderFormula('>'), name: '大于' },
    { latex: '\\leq', display: renderFormula('\\leq'), name: '小于等于' },
    { latex: '\\geq', display: renderFormula('\\geq'), name: '大于等于' },
    { latex: '\\ll', display: renderFormula('\\ll'), name: '远小于' },
    { latex: '\\gg', display: renderFormula('\\gg'), name: '远大于' },
    { latex: '\\approx', display: renderFormula('\\approx'), name: '约等于' },
    { latex: '\\equiv', display: renderFormula('\\equiv'), name: '恒等于' },
    { latex: '\\sim', display: renderFormula('\\sim'), name: '相似' },
    { latex: '\\propto', display: renderFormula('\\propto'), name: '正比于' },
    { latex: '\\in', display: renderFormula('\\in'), name: '属于' },
    { latex: '\\notin', display: renderFormula('\\notin'), name: '不属于' },
    { latex: '\\subset', display: renderFormula('\\subset'), name: '包含于' },
    { latex: '\\supset', display: renderFormula('\\supset'), name: '包含' }
  ],
  arrow: [
    { latex: '\\leftarrow', display: renderFormula('\\leftarrow'), name: '左箭头' },
    { latex: '\\rightarrow', display: renderFormula('\\rightarrow'), name: '右箭头' },
    { latex: '\\leftrightarrow', display: renderFormula('\\leftrightarrow'), name: '双向箭头' },
    { latex: '\\Leftarrow', display: renderFormula('\\Leftarrow'), name: '左双线箭头' },
    { latex: '\\Rightarrow', display: renderFormula('\\Rightarrow'), name: '右双线箭头' },
    { latex: '\\Leftrightarrow', display: renderFormula('\\Leftrightarrow'), name: '双向双线箭头' },
    { latex: '\\uparrow', display: renderFormula('\\uparrow'), name: '上箭头' },
    { latex: '\\downarrow', display: renderFormula('\\downarrow'), name: '下箭头' }
  ],
  special: [
    { latex: '\\partial', display: renderFormula('\\partial'), name: '偏导数' },
    { latex: '\\nabla', display: renderFormula('\\nabla'), name: '梯度' },
    { latex: '\\angle', display: renderFormula('\\angle'), name: '角' },
    { latex: '\\triangle', display: renderFormula('\\triangle'), name: '三角形' },
    { latex: '\\square', display: renderFormula('\\square'), name: '方框' },
    { latex: '\\perp', display: renderFormula('\\perp'), name: '垂直' },
    { latex: '\\parallel', display: renderFormula('\\parallel'), name: '平行' },
    { latex: '\\degree', display: renderFormula('\\degree'), name: '度' },
    { latex: '\\emptyset', display: renderFormula('\\emptyset'), name: '空集' },
    { latex: '\\forall', display: renderFormula('\\forall'), name: '对于所有' },
    { latex: '\\exists', display: renderFormula('\\exists'), name: '存在' },
    { latex: '\\neg', display: renderFormula('\\neg'), name: '非' }
  ]
}

// 示例公式
const examples = [
  { latex: '\\frac{a}{b}', name: '简单分数' },
  { latex: 'x^{2}', name: '平方' },
  { latex: '\\sqrt{x}', name: '平方根' },
  { latex: '\\sum_{i=1}^{n} i', name: '求和' },
  { latex: '\\int_{0}^{1} x^2 dx', name: '定积分' },
  { latex: '\\lim_{x \\to \\infty} f(x)', name: '极限' },
  { latex: '\\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}', name: '一元二次方程' },
  { latex: 'e^{i\\pi} + 1 = 0', name: '欧拉公式' },
  { latex: '\\sin^2(x) + \\cos^2(x) = 1', name: '三角恒等式' },
  { latex: '\\binom{n}{k} = \\frac{n!}{k!(n-k)!}', name: '组合数' }
]

const currentSymbols = computed(() => {
  return symbols[currentTab.value] || []
})

function renderFormula(latex) {
  try {
    return katex.renderToString(latex, {
      throwOnError: false,
      displayMode: false
    })
  } catch (error) {
    return latex
  }
}

function updatePreview() {
  if (!formula.value.trim()) {
    renderedFormula.value = ''
    return
  }
  
  try {
    renderedFormula.value = katex.renderToString(formula.value, {
      throwOnError: false,
      displayMode: true
    })
  } catch (error) {
    renderedFormula.value = `<span style="color: red;">公式语法错误</span>`
  }
}

function insertSymbol(latex) {
  // 在光标位置插入符号
  const textarea = document.querySelector('.formula-input')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const before = formula.value.substring(0, start)
  const after = formula.value.substring(end)
  
  // 智能添加空格
  const needSpaceBefore = before && !/\s$/.test(before)
  const needSpaceAfter = after && !/^\s/.test(after)
  
  const spaceBefore = needSpaceBefore ? ' ' : ''
  const spaceAfter = needSpaceAfter ? ' ' : ''
  
  formula.value = before + spaceBefore + latex + spaceAfter + after
  
  // 移动光标到插入内容后面
  setTimeout(() => {
    const newPos = start + spaceBefore.length + latex.length + spaceAfter.length
    textarea.setSelectionRange(newPos, newPos)
    textarea.focus()
  }, 10)
  
  // watch 会自动调用 updatePreview，不需要手动调用
}

function handleInsert() {
  if (!formula.value.trim()) return
  emit('insert', formula.value)
  handleClose()
}

function handleClose() {
  emit('close')
}
</script>

<style lang="scss" scoped>
.math-editor-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  padding: 20px;
}

.math-editor-container {
  background: white;
  border-radius: 16px;
  width: 100%;
  max-width: 900px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.math-editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
  
  h3 {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin: 0;
  }
  
  .close-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: none;
    border: none;
    border-radius: 50%;
    color: #999;
    font-size: 28px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: #f5f5f5;
      color: #333;
    }
  }
}

.math-editor-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
  
  .section-label {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
    
    .help-text {
      font-size: 12px;
      font-weight: normal;
      color: #999;
      margin-left: 8px;
    }
    
    .help-badge {
      display: inline-block;
      padding: 2px 10px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 12px;
      font-size: 11px;
      font-weight: 500;
    }
  }
}

.preview-section {
  margin-bottom: 24px;
  
  .preview-box {
    min-height: 120px;
    padding: 24px;
    background: linear-gradient(135deg, #f9fafb 0%, #ffffff 100%);
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    
    &:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
    }
    
    .formula-preview {
      font-size: 28px;
      color: #333;
      width: 100%;
      text-align: center;
      
      :deep(.katex) {
        font-size: 1.2em;
      }
    }
    
    .preview-placeholder {
      text-align: center;
      color: #999;
      
      svg {
        margin-bottom: 16px;
      }
      
      p {
        margin: 0 0 8px 0;
        font-size: 14px;
        color: #666;
        
        &.sub-text {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.input-section {
  margin-bottom: 24px;
  
  .formula-input {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    font-family: 'Courier New', monospace;
    resize: vertical;
    transition: all 0.2s;
    
    &:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    &::placeholder {
      color: #bbb;
    }
  }
}

.symbols-section {
  margin-bottom: 24px;
  
  .symbols-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
    overflow-x: auto;
    
    &::-webkit-scrollbar {
      height: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ddd;
      border-radius: 2px;
    }
    
    .tab-btn {
      padding: 6px 16px;
      background: #f5f7fa;
      color: #666;
      border: 1px solid transparent;
      border-radius: 20px;
      font-size: 13px;
      white-space: nowrap;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #e8ecf1;
      }
      
      &.active {
        background: #ede7f6;
        color: #667eea;
        border-color: #667eea;
        font-weight: 500;
      }
    }
  }
  
  .symbols-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
    gap: 8px;
    
    .symbol-btn {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #f3f4f6;
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
      }
      
      :deep(.katex) {
        font-size: 18px;
      }
    }
  }
}

.examples-section {
  .examples-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    
    .example-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      padding: 12px 16px;
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #f3f4f6;
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
      }
      
      .example-preview {
        :deep(.katex) {
          font-size: 16px;
        }
      }
      
      .example-label {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.math-editor-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #eee;
  
  .btn {
    padding: 10px 24px;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    
    &.btn-cancel {
      background: #f5f7fa;
      color: #666;
      
      &:hover {
        background: #e8ecf1;
      }
    }
    
    &.btn-insert {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      
      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}

@media (max-width: 768px) {
  .math-editor-container {
    max-height: 100vh;
    border-radius: 0;
  }
  
  .symbols-grid {
    grid-template-columns: repeat(auto-fill, minmax(50px, 1fr)) !important;
  }
}
</style>

